﻿using LxBasic;
using System.Windows;
using System.Windows.Media;

namespace LxCFD
{
    public class ColorRange
    {
        public ColorRange()
        {
            Segment = 32;
        }
        private int _Segment;
        public int Segment
        {
            get => _Segment;
            set
            {
                _Segment = value;
                ColorBarColors = GetRainbowColors(value);
                ColorBarBrush = GetSteppedGradientBrush(ColorBarColors);
            }
        }
        public MinMaxRange Range = new MinMaxRange();
        public Color[] ColorBarColors;
        public LinearGradientBrush ColorBarBrush { get; set; }

        public LinearGradientBrush GetSteppedGradientBrush(Color[] colors)
        {
            var brush = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(1, 0) };
            double n = colors.Length;
            for (int i = 0; i < colors.Length; i++)
            {
                var gs0 = new GradientStop(colors[i], i / n);
                var gs1 = new GradientStop(colors[i], (i + 1) / n);
                brush.GradientStops.Add(gs0);
                brush.GradientStops.Add(gs1);
            }
            return brush;
        }
        public Color[] GetRainbowColors(int seg)
        {
            Color[] c = new Color[seg];
            float segd = seg - 1;
            for (int i1 = 0; i1 < seg; i1++)
            {
                float pos = i1 / segd;
                c[i1] = Color.FromRgb(r(pos), g(pos), b(pos));
            }
            return c;
            byte r(float p)
            {
                if (p < 0.5) return 0;
                if (p < 0.75) return (byte)((p - 0.5) * (255 * 4));
                return 255;
            }
            byte g(float p)
            {
                if (p < 0.25) return (byte)(p * (255 * 4));
                if (p < 0.75) return 255;
                return (byte)(255 - (p - 0.75) * (255 * 4));
            }
            byte b(float p)
            {
                if (p < 0.25) return 255;
                if (p < 0.5) return (byte)(255 - (p - 0.25) * (255 * 4));
                return 0;
            }
        }

    }


}
